import { ElMessage, ElMessageBox } from 'element-plus'
import type { ElMessageBoxOptions } from 'element-plus'

/**
 * 回调到
 * @param callback 执行函数
 * @param options 提示配置
 * @example
 * confirm(
 *   async () => {
 *     loading.value = true
 *     const res = await props.api.del({
 *       id: row.fileId!
 *     })
 *     loading.value = false
 *     if (res.success) {
 *       onSearch()
 *     }
 *     return res.success
 *   },
 *   {
 *     desc: row.fileName
 *   }
 * )
 */
export function confirm<T extends () => Promise<boolean>>(
  callback: T,
  options: ElMessageBoxOptions & {
    /** 自动拼接的提示词, "确认要${resetDesc}【${desc}】吗？" */
    desc?: string
    /** 完整的提示信息 */
    message?: string
    /** 动作词, 默认是 删除 */
    resetDesc?: string
    /** 成功提示语 */
    successMsg?: string
    /**
     * 失败提示语, 已弃用, 自定提示后返回false即可
     * @deprecated
     */
    errorMsg?: string
  } = {}
) {
  const desc = options.desc ? `【${options.desc}】` : '该数据'
  const defaultOptions = {
    message:
      options.message || `确认要${options.resetDesc || '删除'}${desc}吗？`,
    title: '提示',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    successMsg: `${options.resetDesc || '删除'}成功`
    // 错误已经在axios中进行处理
    // errorMsg: '删除失败'
  }
  const { successMsg, ...elementMessageBoxOptions } = {
    ...defaultOptions,
    ...options
  }

  const beforeClose: ElMessageBoxOptions['beforeClose'] = async (
    action,
    instance,
    done
  ) => {
    if (action !== 'confirm') {
      return done()
    }
    instance.confirmButtonLoading = true

    if (await callback()) {
      successMsg &&
      ElMessage({
        type: 'success',
        message: successMsg
      })
    }
    done()
    // } catch {
    //   errorMsg &&
    //     ElMessage({
    //       type: 'error',
    //       message: errorMsg
    //     })
    // }
    instance.confirmButtonLoading = false
  }
  elementMessageBoxOptions.beforeClose = beforeClose
  ElMessageBox.confirm('', elementMessageBoxOptions as any)
}
